package com.thinkwide.data.filter;

import com.thinkwide.data.servlet.MFServletManager;
import com.thinkwide.data.core.MFPath;
import com.thinkwide.data.debug.MFDebug;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class MFServletFilter implements Filter {

    private ServletContext servletContext;
    private static MFServletManager manager;

    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        String url = ((HttpServletRequest) request).getRequestURI();
        //System.out.println(url);
        if (url.indexOf(".") < 0) {
            if (manager == null) {
                try {
                    manager = new MFServletManager((HttpServletRequest) request, (HttpServletResponse) response, servletContext);
                    String path = MFPath.getDirFromClassLoader() + MFPath.fseparator + "mfservlet.xml";
                    manager.loadConfig(path);
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }
            }

            try {

                if (manager.hasServlet(url)) {
                    manager.updateState((HttpServletRequest) request, (HttpServletResponse) response, servletContext);
                    manager.runServlet(url);
                    chain.doFilter(request, response);
                } else
                    chain.doFilter(request, response);

            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        } else
            chain.doFilter(request, response);

    }

    public void init(FilterConfig config) throws ServletException {
        MFDebug.println("启动后台Servlet过滤器服务...");
        servletContext = config.getServletContext();
    }

}

